package com.fjh.springboot_01.mapper;

import com.fjh.springboot_01.pojo.homework.HomeworkAnswer;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface HomeworkAnswerMapper {
    @Insert("INSERT INTO homework_answer (homework_id, question_id, student_id, " +
            "answer_content, create_time, update_time) " +
            "VALUES (#{homeworkId}, #{questionId}, #{studentId}, " +
            "#{answerContent}, NOW(), NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(HomeworkAnswer answer);

    @Select("SELECT ha.*, u.username as student_name " +
            "FROM homework_answer ha " +
            "LEFT JOIN user u ON ha.student_id = u.id " +
            "WHERE ha.homework_id = #{homeworkId} AND ha.question_id = #{questionId}")
    @Results({
        @Result(column = "student_name", property = "studentName")
    })
    List<HomeworkAnswer> findByHomeworkAndQuestionId(
        @Param("homeworkId") Integer homeworkId,
        @Param("questionId") Integer questionId
    );

    @Select("SELECT ha.*, u.username as student_name " +
            "FROM homework_answer ha " +
            "LEFT JOIN user u ON ha.student_id = u.id " +
            "WHERE ha.homework_id = #{homeworkId} AND ha.student_id = #{studentId}")
    @Results({
        @Result(column = "student_name", property = "studentName")
    })
    List<HomeworkAnswer> findByHomeworkAndStudentId(
        @Param("homeworkId") Integer homeworkId,
        @Param("studentId") Integer studentId
    );

    @Update("UPDATE homework_answer SET teacher_comment = #{teacherComment}, " +
            "score = #{score}, update_time = NOW() " +
            "WHERE id = #{id}")
    void updateTeacherFeedback(
        @Param("id") Integer id,
        @Param("teacherComment") String teacherComment,
        @Param("score") Integer score
    );

    @Update("UPDATE homework_answer SET answer_content = #{answerContent}, " +
            "update_time = NOW() WHERE id = #{id}")
    void updateStudentAnswer(
        @Param("id") Integer id,
        @Param("answerContent") String answerContent
    );

    @Select("SELECT ha.*, u.username as student_name " +
            "FROM homework_answer ha " +
            "LEFT JOIN user u ON ha.student_id = u.id " +
            "WHERE ha.homework_id = #{homeworkId}")
    @Results({
        @Result(column = "student_name", property = "studentName")
    })
    List<HomeworkAnswer> findByHomeworkId(@Param("homeworkId") Integer homeworkId);

    @Select("SELECT ha.*, u.username as student_name " +
            "FROM homework_answer ha " +
            "LEFT JOIN user u ON ha.student_id = u.id " +
            "WHERE ha.id = #{id}")
    @Results({
        @Result(column = "student_name", property = "studentName")
    })
    HomeworkAnswer findById(@Param("id") Integer id);
} 